package com.cci.kangdao.service.impl;

import com.cci.kangdao.aop.UserThreadLocal;
import com.cci.kangdao.dao.AttendanceRecordTDao;
import com.cci.kangdao.dao.model.AttendanceRecordT;
import com.cci.kangdao.dto.request.AttendanceRequest;
import com.cci.kangdao.dto.request.AttendanceUserStatisticsRequest;
import com.cci.kangdao.dto.response.AttendanceResponse;
import com.cci.kangdao.dto.response.AttendanceUserStatisticsResponse;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.AttendanceRecordService;
import com.cci.kangdao.utilTool.BeanUtils;
import com.cci.kangdao.utilTool.LocalTimeUtil;
import com.cci.kangdao.utilTool.ParameterTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @description: 考勤统计服务实现类
 * @author: zyf
 * @create: 2021-05-24
 */
@Service
public class AttendanceRecordImpl implements AttendanceRecordService {
    private Logger log = Logger.getLogger(this.getClass().getName());
    @Resource
    private AttendanceRecordTDao attendanceRecordTDao;
    @Autowired
    private RedisClientUtils redisClientUtils;

    @Override
    public ModelAndView getAttendance(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) {

        String currentDay = LocalTimeUtil.getFormatterRealCurrentTime("yyyy-MM-dd");

        Long userId = UserThreadLocal.get().getId();
        List<AttendanceResponse> list = attendanceRecordTDao.selectByDay(currentDay, userId);
        log.info("getAttendance.aspx接口参数。currentDay:"+currentDay+",userId:"+userId);
        ParameterTool.writeSuccessResponse(response, list);
        return null;
    }

    @Override
    public void uploadAttendance(AttendanceRequest attendanceRequest, HttpServletRequest request, HttpServletResponse response) {
        //判断参数是否有效
        String currentTime = LocalTimeUtil.getRealCurrentTime();
        String key = "attendanceSyncUpload" + UserThreadLocal.get().getId();

        if (redisClientUtils.exists(key)) {
            ParameterTool.writeSuccessResponse(response);
            return;
        } else {
            redisClientUtils.set(key, UserThreadLocal.get().getId() + "", 0);
        }

        try {
            if (Objects.isNull(attendanceRequest.getId())) {
                if (StringUtils.isBlank(attendanceRequest.getStartWorkTime())) {
                    //判断结束时间是否有值
                    ParameterTool.writeErrorResponse(response, -130);
                    return;
                }
                if (StringUtils.isBlank(attendanceRequest.getStartWorkLocation())) {
                    //判断结束时间是否有值
                    ParameterTool.writeErrorResponse(response, -133);
                    return;
                }
                long durationMinutes = LocalTimeUtil.getDurationMinutes(currentTime, attendanceRequest.getStartWorkTime());
                log.info("1.当前用户id："+UserThreadLocal.get().getId()+",durationMinutes:"+durationMinutes);
                if (durationMinutes > 1 || durationMinutes < -1) {
                    ParameterTool.writeErrorResponse(response, -132, currentTime);
                    return;
                }

                //判断当前没有保存
                AttendanceRecordT recordT = new AttendanceRecordT();
                BeanUtils.copy(attendanceRequest, recordT);
                recordT.setUserId(UserThreadLocal.get().getId());
                recordT.setCreator(UserThreadLocal.get().getId());
                recordT.setCreateTime(currentTime);
                recordT.setAttendanceDate(LocalTimeUtil.getFormatterRealCurrentTime("yyyy-MM-dd"));
                attendanceRecordTDao.insertSelective(recordT);

            } else {
                //进行更新操作的
                if (StringUtils.isBlank(attendanceRequest.getEndWorkTime())) {
                    //判断结束时间是否有值
                    ParameterTool.writeErrorResponse(response, -131, "结束时间不能为空");
                    return;
                }

                if (StringUtils.isBlank(attendanceRequest.getEndWorkLocation())) {
                    //判断结束时间是否有值
                    ParameterTool.writeErrorResponse(response, -133);
                    return;
                }
                long durationMinutes = LocalTimeUtil.getDurationMinutes(currentTime, attendanceRequest.getEndWorkTime());
                log.info("2.当前用户id："+UserThreadLocal.get().getId()+",durationMinutes:"+durationMinutes);
                if (durationMinutes > 1 || durationMinutes < -1) {
                    ParameterTool.writeErrorResponse(response, -132, currentTime);
                    return;
                }
                AttendanceRecordT oldRecord = attendanceRecordTDao.selectByPrimaryKey(attendanceRequest.getId());
                //判断下班打卡时间是否提交
                if (oldRecord != null && StringUtils.isNotBlank(oldRecord.getEndWorkTime())) {
                    ParameterTool.writeErrorResponse(response, -134);
                    return;
                }

                AttendanceRecordT recordT = new AttendanceRecordT();
                //获取时间差
                Long total = LocalTimeUtil.getDurationMinutes(oldRecord.getStartWorkTime(), attendanceRequest.getEndWorkTime());
                BeanUtils.copy(attendanceRequest, recordT);
                recordT.setUpdator(UserThreadLocal.get().getId());
                recordT.setUpdateTime(currentTime);
                //获取时间差
                recordT.setDuration(new BigDecimal(total / (double) 60).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                attendanceRecordTDao.updateByPrimaryKeySelective(recordT);
            }
            ParameterTool.writeSuccessResponse(response);
        } catch (Exception e) {
            log.error(e);
            ParameterTool.writeErrorResponse(response);
        } finally {
            redisClientUtils.delkey(key);
        }
    }

    @Override
    public void getAttendanceUserStatistics(AttendanceUserStatisticsRequest statisticsRequest, HttpServletRequest request, HttpServletResponse response) {
        //判断参数值是否为空，开始结束时间或月份不能都唯空
        if (StringUtils.isBlank(statisticsRequest.getStartTime()) && StringUtils.isBlank(statisticsRequest.getEndTime()) && StringUtils.isBlank(statisticsRequest.getMonth())){
            ParameterTool.writeErrorResponse(response,-5);
            return;
        }
        log.info("getUserAttendanceList.aspx接口参数打印：startTime:" + statisticsRequest.getStartTime() + ",endTime:" + statisticsRequest.getEndTime() +
                ",month:" + statisticsRequest.getMonth() + ",userId:" + UserThreadLocal.get().getId());
        statisticsRequest.setUserId(UserThreadLocal.get().getId());
        //查询汇总数据
        AttendanceUserStatisticsResponse statisticsResponse = attendanceRecordTDao.selectTotalByUserId(statisticsRequest);
        //查询按周或月查询逻辑
        Map<String, Map<String, List<AttendanceResponse>>> map = attendanceRecordTDao.selectInfoByUserId(statisticsRequest);
        //按日期进行排序
        Map<String, List<AttendanceResponse>> sortResult = new LinkedHashMap<>();
        map.entrySet()
                .stream().sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> sortResult.put(x.getKey(), x.getValue().get("list")));
        statisticsResponse.setInfos(sortResult);

        //获取时间差
        statisticsResponse.setAverage(new BigDecimal((float) (statisticsResponse.getAverage() / (statisticsResponse.getAbsenceDays() + statisticsResponse.getAttendanceDays()))).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        ParameterTool.writeSuccessResponse(response, statisticsResponse);

    }
}
